#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <aht10.h>
#include <as608.h>
#include <rtdbg.h>
#include <rtdef.h>
#include <Lock.h>
#include <send_all_control.h>

#define KEY_UP_NUM          GET_PIN(C,  5)
#define KEY_DOWN_NUM        GET_PIN(C,  1)
#define KEY_LEFT_NUM          GET_PIN(C,  0)
#define KEY_RIGHT_NUM        GET_PIN(C,  4)
#define AS60X_UART_NAME "uart2"
#define AS60X_WAK_PIN        GET_PIN(G, 4)
#define EVENT_KEY_UP        (1 << 0)
#define EVENT_KEY_DOWN      (1 << 1)
#define EVENT_KEY_RIGHT     (1 << 2)
#define EVENT_FP_TOUCH       (1 << 3)

rt_uint16_t page_id = 0x02;
rt_uint16_t mat_score = 0;
extern struct rt_event *fp_event_ptr;
static struct rt_event key_event; // 按键事件
static rt_bool_t is_initialized = RT_FALSE;
volatile rt_bool_t is_verifying = RT_FALSE;
rt_timer_t unlock_timer;
as60x_ack_type_t yanzheng;

/* 上键中断处理 */
void key_up_handler(void *args)
{
    if (is_initialized) {
        rt_event_send(&key_event, EVENT_KEY_UP);
    }

}

/* 下键中断处理 */
void key_down_handler(void *args)
{
    if (is_initialized) {
        rt_event_send(&key_event, EVENT_KEY_DOWN);
    }
}

/* 右键中断处理 */
void key_right_handler(void *args)
{
    if (is_initialized) {
        rt_event_send(&key_event, EVENT_KEY_RIGHT);
    }
}

/*void fp_touch_handler(void *args)
{
    if (is_initialized) {
        rt_event_send(&key_event, EVENT_FP_TOUCH);
    }
}*/

void fp_touch_handler(void *args)
{
    if (is_initialized && fp_event_ptr && is_verifying) {
        rt_event_send(fp_event_ptr, EVENT_FP_TOUCH);
    }
}

void ALL_Init()
{
    if (is_initialized) return;
    rt_kprintf("Event object address: 0x%p\n", &key_event);
    rt_err_t ret = rt_event_init(&key_event, "key_evt", RT_IPC_FLAG_FIFO);
    rt_kprintf("Event type: %d\n", rt_object_get_type(&key_event.parent.parent));
    if (ret != RT_EOK) {
        LOG_E("Event init failed: %d", ret);
        return;
    }
    fp_wak_evt_reg(&key_event, EVENT_FP_TOUCH);
    as60x_set_hand_shake_baud(57600);
    as60x_init(AS60X_UART_NAME);

    rt_pin_mode(KEY_UP_NUM, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY_DOWN_NUM, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY_LEFT_NUM, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY_RIGHT_NUM, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(AS60X_WAK_PIN, PIN_MODE_INPUT_PULLDOWN);



    /* 绑定中断处理函数 */
    rt_pin_attach_irq(KEY_UP_NUM, PIN_IRQ_MODE_FALLING, key_up_handler, RT_NULL);
    rt_pin_attach_irq(KEY_DOWN_NUM, PIN_IRQ_MODE_FALLING, key_down_handler, RT_NULL);
    rt_pin_attach_irq(KEY_RIGHT_NUM, PIN_IRQ_MODE_FALLING, key_right_handler, RT_NULL);
    rt_pin_attach_irq(AS60X_WAK_PIN, PIN_IRQ_MODE_RISING, fp_touch_handler, RT_NULL);

    rt_thread_mdelay(10);

    /* 使能中断 */
    rt_pin_irq_enable(KEY_UP_NUM, PIN_IRQ_ENABLE);
    rt_pin_irq_enable(KEY_DOWN_NUM, PIN_IRQ_ENABLE);
    rt_pin_irq_enable(KEY_RIGHT_NUM, PIN_IRQ_ENABLE);
    rt_pin_irq_enable(AS60X_WAK_PIN, PIN_IRQ_ENABLE);

/*//     自动锁定定时器
    unlock_timer = rt_timer_create("auto_lock", timer_callback,
                                  NULL, 5000, RT_TIMER_FLAG_ONE_SHOT);

//     创建处理线程
    rt_thread_t tid = rt_thread_create("fp_lock", mensuo_thread_entry,
                                      NULL, 2048, 25, 10);*/
//    rt_thread_startup(tid);
    is_initialized = RT_TRUE;
    is_verifying = RT_FALSE; // 初始化验证状态
}

//按下按键，录入指纹
void UP_FINGER_STR()
{
    rt_uint8_t retry = 0;
    as60x_ack_type_t ret1;
    do {
        ret1 = as60x_str_fp_to_flash(page_id);
        if (ret1 == AS60X_CMD_OK) {
            rt_kprintf("Enroll success!\n");
            break;
        } else {
            rt_kprintf("Retrying enrollment... (%d/3)\n", retry+1);
            rt_thread_mdelay(1000);
            retry++;
        }
    } while (retry < 3);
    if (ret1 != AS60X_CMD_OK) {
        LOG_E("Enroll failed after 3 attempts! Code: 0x%04X", ret1);
    }
}

void timer_callback(void *parameter)
{
    lock();
    rt_kprintf("Auto relock activated\n");
}

rt_err_t verify_fingerprint(void)
{
    is_verifying = RT_TRUE; // 开始验证流程
    // 调用指纹验证函数
    yanzheng = as60x_search_fp_in_flash(&page_id, &mat_score);
    is_verifying = RT_FALSE; // 结束验证流程
/*    rt_kprintf("Fingerprint verified! ID: %d\n", page_id);
    return RT_EOK;*/
    if (yanzheng == AS60X_CMD_OK) {
        rt_kprintf("Verify success! Score: %d\n", mat_score);
        return RT_EOK;
    } else {
        rt_kprintf("Verify failed! Code: 0x%04X\n", yanzheng);
        return -RT_ERROR;
    }
}

//解锁
void jiesuo()
{
//    as60x_ack_type_t result = as60x_search_fp_in_flash(&page_id, &mat_score);
    rt_kprintf("Unlocking...\r\n");
    if(verify_fingerprint() == RT_EOK)
    {
        rt_kprintf("yi jie suo\r\n");
    }
}

rt_err_t delete_fingerprint()
{
    rt_kprintf("Now test delet the fingerprint..\r\n");
    as60x_delet_fp_n_id(page_id, 1);
    return RT_EOK;
}

void lock()
{
//    sg90_set_angle(&my_sg90_config, 0.0);
}

/* 主处理线程 ------------------------------------------------------------*/
void mensuo_thread_entry(void *parameter)
{
    rt_uint32_t recv;
    ALL_Init();
    while (1) {
        if (rt_event_recv(&key_event,
            EVENT_KEY_UP | EVENT_KEY_DOWN | EVENT_KEY_RIGHT | EVENT_FP_TOUCH,
            RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR,
            RT_WAITING_FOREVER, &recv) == RT_EOK) {

            if (recv & EVENT_KEY_UP) {
                UP_FINGER_STR(); // 录入到ID 1
            }
            else if (recv | EVENT_KEY_RIGHT) {
                rt_kprintf("1");
                verify_fingerprint();
                if (verify_fingerprint() == RT_EOK) {
                    jiesuo();
                    rt_timer_start(unlock_timer);
                }
            }
            else if (recv & EVENT_KEY_DOWN) {
                delete_fingerprint(); // 删除ID.
            }
            else if (recv & EVENT_FP_TOUCH) {
                // 当未在验证流程时忽略触摸事件
                rt_kprintf("未触发验证流程，忽略指纹输入...\r\n");
            }
        }
//        rt_thread_mdelay(10);
    }
}
